package org.groupg;

import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.openxml4j.opc.PackageAccess;
import org.apache.poi.poifs.crypt.EncryptionInfo;
import org.apache.poi.poifs.crypt.EncryptionMode;
import org.apache.poi.poifs.crypt.Encryptor;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

/**
 * 为文件设置密码
 */
public class SetPassword {
    private final static Logger log = LoggerFactory.getLogger(SetPassword.class);

    // 通过输入流与输出流将excel 加密
    public static void setPassword4OOXML(InputStream inputStream, OutputStream outputStream, String password) {
        try {
            POIFSFileSystem fs = new POIFSFileSystem();
            EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile);
            Encryptor enc = info.getEncryptor();
            enc.confirmPassword(password);
            try (OPCPackage opc = OPCPackage.open(inputStream);
                 OutputStream os = enc.getDataStream(fs)) {
                opc.save(os);
            }
            fs.writeFilesystem(outputStream);
        } catch (Exception e) {
            log.error("setPwd4OOXML ex : {}" , e.getMessage() , e);
        }
    }

    // 通过输入流与输出流将 word 加密
    public static void setPassword4OfficeFile(String path, String password) {
        try {
            POIFSFileSystem fs = new POIFSFileSystem();
            EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile);
            Encryptor enc = info.getEncryptor();
            enc.confirmPassword(password);
            try (OPCPackage opc = OPCPackage.open(new File(path), PackageAccess.READ_WRITE);
                 OutputStream os = enc.getDataStream(fs)) {
                opc.save(os);
            }
            try (FileOutputStream fos = new FileOutputStream(path)) {
                fs.writeFilesystem(fos);
            }
        } catch (Exception e) {
            log.error("setPwd office file ex : {}", e.getMessage() , e);
        }
    }

    public static void main(String[] args) throws FileNotFoundException {
        // Path path = Paths.get("./target/classes/newPassWord.xlsx");
        File file = new File("./target/classes/");
        if (!file.exists()) {
            file.mkdirs();
        }
        setPassword4OOXML(new FileInputStream(new File("./target/classes/newPassWord.xlsx")), new FileOutputStream(new File("./target/classes/newPassWord1.xlsx")), "admin");
    }
}
